package com.mlming.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mlming.springboot.consts.MallConst;
import com.mlming.springboot.dao.ShippingMapper;
import com.mlming.springboot.enums.ResponseEnum;
import com.mlming.springboot.form.ShippingForm;
import com.mlming.springboot.pojo.Shipping;
import com.mlming.springboot.service.ShippingService;
import com.mlming.springboot.vo.ResponseVo;
import com.mlming.springboot.vo.ShippingVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ShippingServiceImpl implements ShippingService {
    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ResponseVo<Map<String, Integer>> addShipping(Integer userId, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(userId);
        int row = shippingMapper.insertSelective(shipping);
        if(row == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        Map<String,Integer> res = new HashMap<>();
        res.put(MallConst.ADD_SHIPPING_RETURN_SHIPPING_ID,shipping.getId());
        return ResponseVo.success(res);
    }

    @Override
    public ResponseVo deleteShipping(Integer userId, Integer shippingId) {
        int row = shippingMapper.deleteByUserIdAndShippingId(userId, shippingId);
        if(row == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo updateShipping(Integer userId, Integer shippingId, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(userId);
        shipping.setId(shippingId);
        int row = shippingMapper.updateByPrimaryKeySelective(shipping);
        if(row == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<PageInfo> getShippingList(Integer userId, Integer pageNum, Integer pageSize) {
        // 调用page-helper分页插件:
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippings = shippingMapper.selectByUserId(userId);
        List<ShippingVo> shippingVos = new ArrayList<>();
        for (Shipping shipping : shippings) {
            ShippingVo shippingVo = new ShippingVo();
            BeanUtils.copyProperties(shipping,shippingVo);
            shippingVos.add(shippingVo);
        }
        // 通过pageHelper加入接口文档中要求的那堆分页参数
        PageInfo pageInfo = new PageInfo(shippings);
        pageInfo.setList(shippingVos);

        return ResponseVo.success(pageInfo);
    }

}
